package com.biao.template;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 自己的连接器
 * @author: chenwenbiao
 * @create: 2020-2-2 12:47
 */
@Component
public class MyConnectionManager {

    /**
     * 这个是最容易出错的点，连接要让每一个线程独立，不然当一个线程的操作，产生异常后，事务回滚，那就会把另一线程的操作也回滚掉，这就产生线程不安全问题
     */
    private ThreadLocal<Connection> connectionThreadLocal = new ThreadLocal<>();

    @Autowired
    private DataSource dataSource;

    public Connection getConnection() {
        Connection connection = this.connectionThreadLocal.get();
        if (null == connection) {
            try {
                Connection connection1 = dataSource.getConnection();
                connectionThreadLocal.set(connection1);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return this.connectionThreadLocal.get();
    }
}
